package com.hp.bon.sgw.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.ConnectException;
import java.util.Properties;
import java.util.concurrent.TimeoutException;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;

import org.slf4j.bridge.SLF4JBridgeHandler;

import com.hp.bon.sgw.Constants.CRMCBResult;
import com.hp.bon.sgw.Constants.ResultCode;
import com.hp.bon.util.EnvUtil;

/**
 * 用log4j类似的工具记录日志，这里定义一些需要共用的logger
 * 
 * @author wuzhih
 * 
 */
public class LogTool {
	private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(LogTool.class);
	/**
	 * 将JDK log 转接到 slfj 同时将console handler 去除
	 */
	public static void installSLF4JBridge() {
		SLF4JBridgeHandler.install();
		Handler consolHandler = null;
		Logger logger = Logger.getLogger("");
		for (Handler hand : logger.getHandlers()) {
			if (hand instanceof ConsoleHandler) {
				consolHandler = hand;
				break;
			}
		}
		if (consolHandler != null) {
			logger.removeHandler(consolHandler);
		}
	}

	/**
	 * 以字符为单位读取文件，常用于读文本，数字等类型的文件
	 */
	public static StringBuilder readFileByLines(String fileName) {
		StringBuilder sb = new StringBuilder();
		// File file = new File(fileName);
		Reader read = null;
		try {
			// 一次读一行
			read = new InputStreamReader(new FileInputStream(fileName), "UTF-8");
			// 读入一行
			BufferedReader reader = new BufferedReader(read);
			String line;
			while ((line = reader.readLine()) != null) {
				// 同样屏蔽掉\r不显示
				sb.append(line + "\r\n");
			}

		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			if (read != null) {
				try {
					read.close();
				} catch (IOException e1) {
				}
			}
		}
		return sb;
	}

	/**
	 * @param propFile
	 * @param props
	 * @param propStream
	 * @throws IOException
	 */
	public static Properties loadPropertyFormFile(String propFile) throws IOException {
		InputStream propStream = null;
		Properties props = new Properties();
		propStream = new FileInputStream(propFile);
		props.load(propStream);
		if (propStream != null) {
			try {
				propStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return props;
	}

	/**
	 * @param propFile
	 * @param props
	 * @param propStream
	 */
	public static void loadProperty(String propFile) {
		InputStream propStream = null;
		Properties props = new Properties();
		try {
			propStream = new FileInputStream(propFile);
			props.load(propStream);
			//lichagnzhen 20130716 替换为环境变量,支持类似backupPath=${SGW_HOME}/backup
			for(Object key:props.keySet())
			{
				String value = (String) props.get(key);
				if(value == null && value.isEmpty())
					continue;
				String newValue = EnvUtil.replaceEnv(value);
				if(newValue != value)
				{
					LOG.info(key+"="+value+",replaceEnv to:"+newValue);
					props.put(key, newValue);
				}
			}
			
			Properties sysProps = System.getProperties();
			sysProps.putAll(props);
			System.setProperties(sysProps);
		} catch (IOException e1) {
			throw new RuntimeException("load err:" + e1);
		} finally {
			if (propStream != null) {
				try {
					propStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	/**
	 * 获取调用外部网元接口时发生的异常对应的错误代码
	 * 
	 * @param e
	 *            异常
	 * @return 错误代码
	 */
	public static int getErrorCodeForBonCallCRMException(Exception e) {
		Throwable cause = e.getCause();
		int retCode = 0;
		if (cause instanceof ConnectException) {
			retCode = CRMCBResult.WS_RCVER_BON_NE_ERR;
		} else if (cause instanceof TimeoutException) {
			retCode = CRMCBResult.WS_SEND_CRM_MSG_TIMEOUT;
		} else {
			retCode = CRMCBResult.WS_SEND_CRM_SYS_ERR;
		}
		return retCode;
	}

	/**
	 * 获取调用外部网元接口时发生的异常对应的错误代码
	 * 
	 * @param e
	 *            异常
	 * @return 错误代码
	 */
	public static int getErrorCodeForBonCallException(Exception e) {
		Throwable cause = e.getCause();
		int retCode = 0;
		if (cause instanceof TimeoutException) {
			retCode = ResultCode.NE_TIMEOUT;
		} else {
			retCode = ResultCode.NE_CANNOT_USE;
		}
		return retCode;
	}
}
